package com.idenger.modules.edu.mobileWeb.pay;


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.enroll.EduEnroll;
import com.idenger.modules.edu.service.income.EduIncomeService;
import com.idenger.modules.edu.web.comm.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.idenger.common.utils.StringUtils;
import com.idenger.modules.edu.entity.income.EduIncome;
import com.idenger.modules.edu.entity.order.EduOrder;
import com.idenger.modules.edu.service.enroll.EduEnrollService;
import com.idenger.modules.edu.service.order.EduOrderService;
import com.idenger.modules.edu.service.shopping.EduShoppingCartService;
import com.idenger.modules.edu.web.utils.PayController;

import net.sf.json.JSONObject;

/* *
 *类名：AlipayConfig
 *功能：基础配置类
 *详细：设置帐户有关信息及返回路径
 *修改日期：2017-04-05
 *说明：
 *以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
 */
@Controller
@RequestMapping(value = "${mobilePath}/edu/pay/aliPay")
public class AlipayController extends PayController{
	
	@Autowired
	private EduOrderService eduOrderService;
	@Autowired
	private EduIncomeService eduIncomeService;
	@Autowired
	private EduEnrollService eduEnrollService;
	@Autowired
	private EduShoppingCartService eduShoppingCartService;
	// 支付宝网关
	public static String log_path = "C:\\";
	

    /** 
     * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
     * @param sWord 要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @RequestMapping(value = "pay")
	public  String pay(EduOrder eduOrder, HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduOrder order = eduOrderService.get(eduOrder.getId());
	   AlipayClient alipayClient = new DefaultAlipayClient(aliGatewayUrl, aliAppid, aliMerchantPrivateKey, "json", aliCharset, aliPayPublicKey, aliSignType);
		//设置请求参数
	   AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
	   alipayRequest.setReturnUrl(aliReturnUrl);
	   alipayRequest.setNotifyUrl(aliNotifyUrl);
	 //商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = order.getTradeNo();
		//付款金额，必填
		String total_amount = order.getPrice();
		//订单名称，必填
		String subject =order.getOrderName();
		//商品描述，可空
		String body = order.getOrderName();
		
		alipayRequest.setBizContent("{\'out_trade_no\':\'"+ out_trade_no +"\'," 
				+ "\'total_amount\':\'"+ total_amount +"\'," 
				+ "\'subject\':\'"+ subject +"\'," 
				+ "\'body\':\'"+ body +"\'," 
				+ "\'product_code\':\'FAST_INSTANT_TRADE_PAY\'}");
		//请求
		try {
			String result = alipayClient.pageExecute(alipayRequest).getBody();
			Map map = new HashMap<>();
			map.put("result", result);
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
			baseResponseMsg.addData(map);
			return renderString(response, baseResponseMsg);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
		baseResponseMsg.addData("支付失败");
		return renderString(response, baseResponseMsg);
   } 
    
    @RequestMapping(value = "index")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model){
		
    	return "modules/edu/pay/index";
    }
    
    @RequestMapping(value = "notify")
    public String notify( HttpServletRequest request, HttpServletResponse response, Model model){
			BaseResponseMsg baseResponseMsg;
    		//获取支付宝POST过来反馈信息
    		Map<String,String> params = new HashMap<String,String>();
    		
    		Map<String,String[]> requestParams = request.getParameterMap();
    		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String[] values = (String[]) requestParams.get(name);
    			String valueStr = "";
    			for (int i = 0; i < values.length; i++) {
    				valueStr = (i == values.length - 1) ? valueStr + values[i]
    						: valueStr + values[i] + ",";
    			}
    			//乱码解决，这段代码在出现乱码时使用
    			try {
					valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			params.put(name, valueStr);
    		}
    		
    		boolean signVerified;
			try {
		        PrintWriter out = response.getWriter();
				signVerified = AlipaySignature.rsaCheckV1(params, aliPayPublicKey, aliCharset, aliSignType);
    		if(signVerified) {//验证成功
    			//商户订单号
    			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
    			//支付宝交易号
    			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
    			JSONObject json = JSONObject.fromObject(params);
    			String result = json.toString();
    			EduOrder eduOrder = eduOrderService.findOrderByTradeNo(out_trade_no);
    			if(StringUtils.isNotBlank(result)){
        			eduOrder.setRemarks(result);
    			}
    			eduOrder.setOrderStatus(Constant.ORDER_STATUS_COMPLETED);
    			eduOrder.setPayStatus(Constant.ORDER_PAYSTATUS_ALREADYPAY);
    			eduOrderService.save(eduOrder);
    			EduIncome eduIncome = new EduIncome();
    			eduIncome.setUserid(eduOrder.getUserid());
    			eduIncome.setPayDate(new Date());
    			eduIncome.setMoney(eduOrder.getPrice());
    			eduIncome.setSource(Constant.INCOME_DICT_SOURCE);
    			eduIncome.setStatus(Constant.INCOME_STATUS_NORMAL);
    			eduIncome.setBusinessid(eduOrder.getId());
    			eduIncome.setIDesc(Constant.INCOME_DICT_DESC);
    			eduIncome.setPaymethod(eduOrder.getPayMethod());
    			eduIncomeService.save(eduIncome);
    			//删除购物车的记录
    			deleteShoppCart(eduOrder.getId(), eduOrder.getUserid());
    	        out.println("success");
    			return "redirect:" + aliReturnHtml;
//    			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
//    			baseResponseMsg.addData("支付成功");
//    			return renderString(response, baseResponseMsg);
    		}else {//验证失败
    	        out.println("fail");
    			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
    			baseResponseMsg.addData("支付失败");
    			return renderString(response, baseResponseMsg);
    			//调试用，写文本函数记录程序运行情况是否正常
    			//String sWord = AlipaySignature.getSignCheckContentV1(params);
    			//AlipayConfig.logResult(sWord);
    		}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		//——请在这里编写您的程序（以上代码仅作参考）——
			baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("支付失败");
			return renderString(response, baseResponseMsg);
    }
    
    public void deleteShoppCart(String orderId,String userId){
		List<EduEnroll> list = eduEnrollService.findListForOrderId(orderId);
			for(EduEnroll eduEnroll :list){
				eduShoppingCartService.deleteShoppoCart(userId, eduEnroll.getCurriculumId());
			}
    }
    
}

